package com.jweb.framework.core.channel;

import com.jweb.framework.core.Context;
import com.jweb.framework.core.CoreException;

public class DefaultTransport<Request , Respones> implements Transport {
	
	private Gateway gateway ;
	private Transform[] encodeTransforms ;
	private Transform[] decodeTransforms ;
	private TransportListener transportListener ;
	
	public DefaultTransport(){
		
	}

	public TransportListener getTransportListener() {
		return transportListener;
	}

	public void setTransportListener(TransportListener transportListener) {
		this.transportListener = transportListener;
	}

	public void setGateway(Gateway gateway) {
		this.gateway = gateway;
	}

	public void setEncodeTransforms(Transform[] encodeTransforms) {
		this.encodeTransforms = encodeTransforms;
	}

	public void setDecodeTransforms(Transform[] decodeTransforms) {
		this.decodeTransforms = decodeTransforms;
	}
	
	public Object submit(Object obj , Context context) throws CommunicationException , CoreException {
		Object recTransformObj = null ;
		Object sendTransformObj = transform(obj , encodeTransforms , context.getProcessId());
		if(getTransportListener() != null){
			getTransportListener().onSend(obj , context, sendTransformObj);
		}
		Object recObj = gateway.sendAndReceive(sendTransformObj, context.getRequestId());
		if(getTransportListener() != null){
			getTransportListener().onReceive(obj , context, recObj);
		}
		if(recObj != null){
			recTransformObj = transform(recObj , decodeTransforms , context.getProcessId());
		}
		return recTransformObj ;
	}
	
	private Object transform(Object obj , Transform[] transform , String processId) throws CoreException {
		Object afterObj = obj ;
		if(transform != null){
			Transform trans[] ;
			int j = (trans = transform).length ;
			for(int i = 0 ; i < j ; i++){
				Transform tran = trans[i];
				afterObj = tran.transform(afterObj , processId);
			}
		}
		return afterObj ;
	}
	
}
